const dayjs = require("dayjs");
const Subscription = require('egg').Subscription;
const { Op, literal, col } = require('sequelize');

class CleanupUnpaidOrders extends Subscription {
  static get schedule() {
    return {
      // 每5秒执行一次
      interval: '30s',
      type: 'worker', // 指定所有的 worker 都需要执行
    };
  }

  async subscribe() {
    console.log('执行定时任务')
    const { ctx, app } = this;

    try {
      console.log(dayjs().format('YYYY-MM-DD HH:mm:ss'))
      // 查找创建时间超过15分钟且未支付的订单
      const unpaidOrders = await ctx.model.Order.findAll({
        where: {
          status_value: 'wait_pay', // 未支付
          create_time: {
            [Op.lt]: dayjs().subtract(3, 'minute').format('YYYY-MM-DD HH:mm:ss')
          }
        },
        include: [
          {
            model: ctx.model.Cycle,
            as: 'cycle'
          },
          {
            model: ctx.model.Ship,
            as: 'ship'
          }
        ]
      });
      console.log('unpaidOrders',unpaidOrders.length)
      for (const order of unpaidOrders) {
        // 获取订单的cycle_id
        const cycleId = order.cycle_id;
        console.log('cycleId',cycleId,order.ship.code)
        // 删除对应的排期记录
        if (cycleId) {
          if (order.ship.code === 'Custom') {
            ctx.service.cycle.deleteById(cycleId);
          } else {
            await this.ctx.model.Cycle.update({
              count: Number(order.cycle.count) + Number(order.count)
            }, {
              where: {
                id: cycleId
              }
            })
          }
        }
        // 更新订单状态为已取消
        order.update({
          status: -1,
          status_value: 'canceled',
          status_name: '已取消'
        });
      }
      this.ctx.logger.info(`Cleaned up ${unpaidOrders.length} unpaid orders`);
    } catch (error) {
      this.ctx.logger.error('Error cleaning up unpaid orders:', error);
    }
  }
}

module.exports = CleanupUnpaidOrders;
